package com.tjp.eight.utils;

import android.os.Handler;
import android.os.Message;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2017/3/3.
 */

public class TimeDown {


    private Timer timer;
    private int count;
    private TimeDownListener timeDownListener;

    public TimeDown(int count, TimeDownListener timeDownListener) {
        this.count = count;
        this.timeDownListener = timeDownListener;
    }

    /**
     * 开始倒计时
     */
    public void start() {
        if (timeDownListener != null)
            timeDownListener.onPrepareCountDown();
        timer = new Timer();
        timer.scheduleAtFixedRate(timerTaskCountDownTime, 0, 1000);
    }
    /**
     * 取消倒计时
     */
    public void cancel() {
        timerTaskCountDownTime.cancel();
        if (timer != null)
            timer.cancel();
    }
    private TimerTask timerTaskCountDownTime = new TimerTask() {

        @Override
        public void run() {
            Message message = new Message();
            message.what = 1;
            handlerCountDown.sendMessage(message);
        }
    };
    private Handler handlerCountDown = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                count--;
                if (count < 0){
                    timer.cancel();
                    if (timeDownListener != null){
                        timeDownListener.onFinishCountDown();
                    }
                    return;
                }
                timeDownListener.onRefreshTime(count);
            }
        }

    };

    /**
     * 倒计时监听
     *
     * @author Jiang
     *
     */
    public interface TimeDownListener {

        /**
         * 执行前
         */
        void onPrepareCountDown();

        /**
         * 刷新时间执行
         *
         * @param second
         *            剩余秒
         */
        void onRefreshTime(int second);

        /**
         * 倒计时结束
         */
        void onFinishCountDown();
    }
}
